package com.azt.back.action.user;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.azt.api.pojo.Authority;
import com.azt.api.pojo.Dept;
import com.azt.api.pojo.Role;
import com.azt.api.pojo.UserFunction;
import com.azt.api.service.FunctionService;
import com.azt.api.service.UserPermissionService;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.utils.RequestUtils;

import net.sf.json.JSONObject;

/**
 * 该视图控制类：用户权限控制
 * @author 查恒  2016年8月5日下午2:59:04
 */
@Controller
@RequestMapping("/user_permission")
public class UserPermissionAction {
	@Autowired
	private UserPermissionService userPermissionService;
	@Autowired
	private FunctionService functionService;
	
	/**
	 * @description 角色列表
	 * @param request
	 * @param pageNo
	 * @param response
	 * @param model
	 * @return
	 * @author 查恒  2016年8月10日下午5:19:55
	 */
	@RequestMapping(value = "/v_rolelist.do" )
	public String UserPermissionRoleList(HttpServletRequest request, Integer pageNo, HttpServletResponse response,ModelMap model){
		Map<String, String> searchMap = RequestUtils.getSearchMap(request);
		String so_urole = searchMap.get("so_urole"); 	
		Pagination UroleByPage = userPermissionService.getRoleModelByPage(pageNo == null ? 1 : pageNo, 10, searchMap);
		model.addAttribute("pagination", UroleByPage);
		if(StringUtils.isNotBlank(so_urole)){
			model.addAttribute("uroleName", so_urole);
		}
		return "permission/urole_list";
	}
	
	
	/**
	 * @description 部门添加和编辑
	 * @param request
	 * @param response
	 * @param udept
	 * @return
	 * @author 查恒  2016年8月10日下午5:19:51
	 */
	@RequestMapping("/o_createdept.do")
	@ResponseBody
	public AjaxJson addUdept(HttpServletRequest request,
			HttpServletResponse response,Dept udept){
		AjaxJson  json = new AjaxJson();
		//判断默认部门名称是否已经存在
/*		String udeptname=udept.getName();
		try {
				//编辑
				if (udept.getId() != null && !"".equals(udept.getId())) {
					if (deptByname != null) {
						if (deptByname.getId() != udept.getId()) {
							json.setSuccess(false);
							json.setMsg("部门名称已存在");
							return json;
						}
					}
					dept.setName(udeptname);
					dept.setCompany(null);
					dept.setIfDefault(udept.getIfDefault());
					dept.setSortNum(udept.getSortNum());
					dept.setUpdatetime(new Date());
					userPermissionService.updateDept(dept);
					json.setMsg("编辑成功");
					json.setSuccess(true);
				} else {
					// 新增
					if (deptByname != null) {
						json.setSuccess(false);
						json.setMsg("部门名称已存在");
						return json;
					}
					udept.setRemoved(0);//默认
					userPermissionService.saveDept(udept);
					json.setMsg("新增成功");
					json.setSuccess(true);
				}
		
		} catch (Exception e) {
			json.setSuccess(false);
			json.setMsg("操作失败");
		}
		*/
		return json;
	} 
	
	
	/**
	 * @description 新增角色的对话框还是编辑角色的对话框
	 * @param request
	 * @param response
	 * @param model
	 * @param udeptId
	 * @param roleId
	 * @return
	 * @author 查恒  2016年8月11日上午10:00:21
	 */
	@RequestMapping(value = "/v_roledialog.do")
	public String roleDialog(HttpServletRequest request, HttpServletResponse response,ModelMap model,Integer roleId){
		Role uroleById=null;
		if(roleId!=null){
			uroleById = userPermissionService.getRoleById(roleId);
		}
		model.addAttribute("Urole", uroleById);
		return "permission/roledialog";
	}
	
	/**
	 * @description 添加角色和权限  或编辑
	 * @param request
	 * @param response
	 * @param role
	 * @return
	 * @author 查恒  2016年8月10日下午4:03:34
	 */
	@ResponseBody
	@RequestMapping(value = "/o_addrole.do")
	public JSONObject roleFunctionAdd(HttpServletRequest request , HttpServletResponse response , Role urole){
		JSONObject  json = new JSONObject();
		String[] funcids =request.getParameterValues("funcids[]");
		try{
		//判断是编辑还是新增角色
		if(urole.getId()!=null){
			Role uroleById = userPermissionService.getRoleById(urole.getId());
			uroleById.setName(urole.getName());
			uroleById.setRoleType(urole.getRoleType());
			uroleById.setSortNum(urole.getSortNum());
			uroleById.setCode(urole.getCode());
			uroleById.setUpdatetime(new Date());
			userPermissionService.updateRole(uroleById);
			//删除角色下的所有权限
			functionService.delAuthorityByRoleId(urole.getId());
			//重新保存权限
			for(String funcid:funcids){
				if(StringUtils.isNotBlank(funcid)){
					UserFunction functionById = functionService.getFuncById(Integer.parseInt(funcid));
					Authority ua=new Authority();
					ua.setUserFunction(functionById);
					ua.setRoleId(uroleById.getId());
					ua.setFunctionId(functionById.getId());
					ua.setUpdatetime(new Date());
					functionService.saveAuthority(ua);
				}
			}
			
			json.put("msg", "编辑角色成功");
		}else{
			//新增
			urole.setRemoved(0);//默认
			urole.setIfDefault(1);
			urole.setCreatetime(new Date());
			urole.setUpdatetime(new Date());
			userPermissionService.saveRole(urole);
			for(String funcid:funcids){
				if(StringUtils.isNotBlank(funcid)){
					UserFunction functionById = functionService.getFuncById(Integer.parseInt(funcid));
					Authority ua=new Authority();
					ua.setUserFunction(functionById);
					ua.setRoleId(urole.getId());
					ua.setFunctionId(functionById.getId());
					ua.setCreatetime(new Date());
					functionService.saveAuthority(ua);
				}
			}
			//保存角色下权限
			json.put("msg", "添加角色成功");
		}
		json.put("success", true);
	   }catch(Exception e){
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", "操作失败");
		}
		return json;
	}
	
	/**
	 * @description 删除角色
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 * @author 查恒  2016年8月11日上午10:04:25
	 */
	@RequestMapping(value="/o_delrole.do")
	@ResponseBody
	public AjaxJson delUrole(HttpServletRequest request, HttpServletResponse response, Integer roleId){
		AjaxJson  json = new AjaxJson();
		try{
			Role roleById = userPermissionService.getRoleById(roleId);
			if(roleById!=null){
				roleById.setRemoved(1);//标记删除
				userPermissionService.updateRole(roleById);
				json.setMsg("删除角色成功");
				json.setSuccess(true);
			}else{
				json.setMsg("删除失败，记录不存在");
				json.setSuccess(false);
			}
		}catch(Exception e){
			e.printStackTrace();
			json.setSuccess(false);
			json.setMsg("删除失败");
		}
		return json;
	}
	
	/**
	 * 添加修改验证code重名
	 * @Title: validateCode 
	 * @Description: TODO
	 * @return
	 * @return: AjaxJson
	 * @author: zhoudongdong 2016年10月8日 上午10:22:34
	 */
	@RequestMapping("/validate_code.do")
	@ResponseBody
	public AjaxJson validateCode(Role role){
		AjaxJson ajaxJson=new AjaxJson();
		try {
			Role roleSelect=userPermissionService.getRoleByCode(role.getCode());
			if(roleSelect!=null){
				ajaxJson.setSuccess(false);
				ajaxJson.setMsg("编号code已存在！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajaxJson.setSuccess(false);
			ajaxJson.setMsg("系统出错");
		}
		return ajaxJson;
	}
}
